package com.alameda.commonpent.commonback.impl;

import com.alameda.base.bo.CommonBackBO;
import com.alameda.commonpent.commonback.api.CommonBackTemplate;
import com.alameda.commonpent.commonback.mapper.CommonBackMapper;
import com.alameda.result.ResultEnum;
import com.alameda.utils.AssertUtils;
import com.alameda.utils.MapUtils;
import com.alameda.utils.PubUtils;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通用后端组件 业务逻辑层 具体实现
 *
 * @author Lv
 * @date 2024/2/19
 */
@SuppressWarnings("all")
@Slf4j
@Component
@MapperScan("com.alameda.commonpent.commonback.mapper")
public class CommonBackTemplateImpl<T> implements CommonBackTemplate<T> {

    @Autowired
    private CommonBackMapper<T> commonBackMapper;

    /**
     * 通用获取详情
     *
     * @param commonBackBO 通用后端业务对象
     * @return
     */
    @Override
    public Map<String, Object> get(CommonBackBO commonBackBO) {
        // 断言具有详情权限
        AssertUtils.isTrue(commonBackBO.getTableEnum().isGet(), ResultEnum.NO_OPERATOR_AUTH);

        // 处理表名称
        String tableName = commonBackBO.getTableEnum().name().toLowerCase();
        String selectFiled = getSelectFiled(tableName, commonBackBO.getTableEnum().filed, commonBackBO.getTableEnum().getPojoPath());
        String where = "and id = " + commonBackBO.getId();

        // 读取数据
        HashMap map = commonBackMapper.get(selectFiled, tableName, where);
        Map<String, Object> dataMap = MapUtils.newHashMap();
        dataMap.put("data", map);
        return dataMap;
    }

    /**
     * 通用逻辑删除
     *
     * @param commonBackBO 通用后端业务对象
     * @return
     */
    @Override
    public Boolean remove(CommonBackBO commonBackBO) {
        // 断言具有删除权限
        AssertUtils.isTrue(commonBackBO.getTableEnum().isDelete(), ResultEnum.NO_OPERATOR_AUTH);

        String where = "and id in ( " + dealIdList(commonBackBO.getIdList()) + " )";
        commonBackMapper.remove(commonBackBO.getTableEnum().name().toLowerCase(), where);
        return Boolean.TRUE;
    }

    /**
     * 处理id集合 (1,2,3,4)
     *
     * @param idList id集合
     * @return
     */
    private String dealIdList(List<Long> idList) {
        return idList.stream()
                .map(item -> item.toString())
                .collect(Collectors.joining(","));
    }

    /**
     * 符号 .
     */
    private static final String DOT = ".";

    /**
     * 实体类后缀
     */
    private static final String DO = "DO";

    /**
     * 序列化编码字段
     */
    private static final String SERIAL_VERSION_UID = "serialVersionUID";

    /**
     * 获取查询字段
     *
     * @param tableName 表名称
     * @param filed     不允许查询的字段
     * @param pojoPath  实体包路径
     * @return
     */
    public String getSelectFiled(String tableName, String filed, String pojoPath) {
        String className = getClassName(tableName);

        // 反射方式获取实体包路径下的类字节码
        Class<?> aClass = getTargetObjectClass(pojoPath, className);

        // 获取并处理字段
        Field[] declaredFields = aClass.getDeclaredFields();

        // 返回字段 返回形式 "a,b,c_d……"
        return Arrays.asList(declaredFields).stream()
                .filter(item -> !SERIAL_VERSION_UID.equalsIgnoreCase(item.getName()))
                .filter(item -> !PubUtils.toUnderScoreCase(item.getName()).equalsIgnoreCase(filed))
                .map(item -> PubUtils.toUnderScoreCase(item.getName()))
                .collect(Collectors.joining(","));
    }

    /**
     * 获取类名称
     *
     * @param tableName 表名称
     * @return
     */
    @Override
    public String getClassName(String tableName) {
        // 包含下划线则转换成驼峰 user_record --> userRecord
        String tableNameCamel = tableName.contains("_") ? PubUtils.toCamelCase(tableName.toLowerCase()) : tableName;

        // 将第一个字母转换为大写
        StringBuffer stringBufferFirst = new StringBuffer();
        StringBuffer stringBufferOther = new StringBuffer();
        char[] chars = tableNameCamel.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i == 0) {
                stringBufferFirst.append((String.valueOf(chars[i]).toUpperCase()));
            } else {
                stringBufferOther.append(chars[i]);
            }
        }
        return stringBufferFirst.append(stringBufferOther).toString();
    }

    /**
     * 获取目标对象反射字节码
     *
     * @param pojoPath  路径
     * @param className 类名称
     * @return
     */
    @Override
    public Class<?> getTargetObjectClass(String pojoPath, String className) {
        Class<?> aClass = null;
        try {
            aClass = Class.forName(pojoPath + DOT + className + DO);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            log.error("无法寻找到类 " + className);
        }
        return aClass;
    }

    /**
     * 物理删除
     *
     * @param deleteSql 删除sql
     * @return
     */
    @Override
    public Integer executeDelete(String deleteSql) {
        return commonBackMapper.executeDelete(deleteSql);
    }
}
